#include"global.h"
#include"mylabel.h"
#include"crecordswid.h"

CRecordsWid::CRecordsWid(const QString &chatRoom, const QString &msg, const QString& time, QWidget *parent)
    : QWidget{parent}
    ,_msg(msg)
    ,_chatRoom(chatRoom)
    ,_time(time)
    ,green(149,236,105)
    ,white(255,255,255)
{
    pixmap.load(AvatarPath.arg(_chatRoom));
    initText();
    //来减少重绘次数
    setAutoFillBackground(false);
}

CRecordsWid::~CRecordsWid()
{
    delete label;
}

QSize CRecordsWid::sizeHint() const {
    QSize size = label->sizeHint();
    size.setWidth(size.width() + 20);
    size.setHeight(size.height() + 30);
    return size;
}

void CRecordsWid::paintEvent(QPaintEvent * event)
{
    QWidget::paintEvent(event);
    QPainter painter(this);
    painter.setRenderHints(QPainter::Antialiasing, true);
    QPen pen(white);
    QBrush brush(white);

    painter.setPen(pen);
    painter.setBrush(brush);
    //绘制头像
    painter.drawPixmap(30, 20, 34, 34, pixmap);

    QFont font("华文细黑", 10);
    font.setWeight(QFont::Light); // 设置为轻量级，这通常类似于细体

    pen.setColor(QColor(150,150,150));
    painter.setPen(pen);
    painter.setFont(font);
    painter.drawText(QRect(74, 15, 200, 30), Qt::TextWordWrap | Qt::AlignLeft, _chatRoom);
    painter.drawText(QRect(this->width() - 100, 15, 200, 30), Qt::TextWordWrap | Qt::AlignLeft, _time);
}

void CRecordsWid::resizeEvent(QResizeEvent *event)
{
    int w = this->width() * 0.8;
    QWidget::resizeEvent(event);
    QSize textRect = label->sizeHint();
    if (w > textAllWidth){
        label->setFixedWidth(textAllWidth);
    }else{
        label->setFixedWidth(w);
    }
    label->setFixedHeight(textRect.height() - 30);
    emit InterfaceUpdate(label->sizeHint());
}

void CRecordsWid::initText()
{
    QFont font("华文细黑", 12);
    font.setWeight(QFont::Light); // 设置为轻量级，这通常类似于细体
    this->setFont(font);
    QFontMetrics metrics(this->font());
    textAllWidth = metrics.horizontalAdvance(_msg) + 20;

    label = new MyLabel(false, _msg, this);
    label->move(LOCATION_X + 25, LOCATION_Y + 20);//位置
}
